using System;
using System.Collections.Generic;
using System.Text;

namespace Weazel.Microblaze.Simulator.Components.Microblaze.Instructions
{
    /// <summary>
    /// Pattern Compare Byte Find
    /// </summary>
    public class Pcmpbf :
      Instruction
    {
        public override int CycleCount
        {
            get { return 1; }
        }

        public Pcmpbf()
            : base("pcmpbf")
        {
        }

        /// <summary>
        /// The contents of register rA is bytewise compared with the contents in 
        /// register rB.
        ///  * rD is loaded with the position of the first matching byte pair, 
        ///    starting with MSB as position 1, and comparing until LSB as position 4
        /// 
        ///  * If none of the byte pairs match, rD is set to 0
        /// </summary>    
        public override void Execute(MicroblazeComponent MicroblazeComponent)
        {
            uint ra = MicroblazeComponent.ReadRegister(SourceRegisterA);
            uint rb = MicroblazeComponent.ReadRegister(SourceRegisterB);

            if ((ra & 0x000000FF) == (rb & 0x000000FF))
                MicroblazeComponent.WriteRegister(DestinationRegister, 1, Address);
            else if ((ra & 0x0000FF00) == (rb & 0x0000FF00))
                MicroblazeComponent.WriteRegister(DestinationRegister, 2, Address);
            else if ((ra & 0x00FF0000) == (rb & 0x00FF0000))
                MicroblazeComponent.WriteRegister(DestinationRegister, 3, Address);
            else if ((ra & 0xFF000000) == (rb & 0xFF000000))
                MicroblazeComponent.WriteRegister(DestinationRegister, 4, Address);
            else
                MicroblazeComponent.WriteRegister(DestinationRegister, 0, Address);
        }

        public override string ToString()
        {
            return string.Format("pcmpbf r{0}, r{1}, r{2}",
              DestinationRegister,
              SourceRegisterA,
              SourceRegisterB
            );
        }
    }
}
